package middleware
import (
	"github.com/labstack/echo"
	// "time"
	"github.com/dgrijalva/jwt-go"
	// "net/http"
	// mw "github.com/labstack/echo/middleware"

	// . "github.com/hb-go/echo-web/conf"
	// "github.com/hb-go/echo-web/middleware/opentracing"
	// "oxy_server/module/cache"
	"oxy_server/module/log"
	
)

func AuthToken(c echo.Context) (*jwt.Token,error) {
	cookie, err := c.Cookie("token")
	if err != nil{
		log.Error("获取token 失败")
		c.JSON(401, map[string]interface{}{
		"msg":   "error",
		"info":   "获取token 失败",
		})
		return nil,err
	}
	token, err := jwt.Parse(cookie.Value,func(token *jwt.Token)(interface{},error){
		return []byte("secret"), nil
	})
	if err != nil{
		log.Error("解密token 失败")
		c.JSON(401, map[string]interface{}{
		"msg":   "error",
		"info":   "解密token 失败",
		})
		return nil,err
	}
	return token,nil
}

func CreateToken(name string, role string, password string) (t string, e error) {
	// Create token
	token := jwt.New(jwt.SigningMethodHS256)

	// Set claims
	claims := token.Claims.(jwt.MapClaims)
	claims["name"] = name
	claims["role"] = role
	claims["password"] = password
	// claims["exp"] = time.Now().Add(time.Minute * 60).Unix()

	// Generate encoded token and send it as response.
	t, e = token.SignedString([]byte("secret"))
	return
}